package cn.stylefeng.guns.modular.gridsystem.annotion.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.guns.core.exception.ServiceException;
import cn.stylefeng.guns.modular.gridsystem.entity.ThirdPartyInterconnection;
import cn.stylefeng.guns.modular.gridsystem.service.ThirdPartyInterconnectionService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;

/**
 * appKey注解校验
 */
@Aspect
@Component
public class AppKeyAop {

    @Autowired
    private ThirdPartyInterconnectionService thirdPartyInterconnectionService;

    /**
     * 数据范围切入点
     */
    @Pointcut("@annotation(cn.stylefeng.guns.modular.gridsystem.annotion.custom.AppKey)")
    private void getAppKeyPointCut() {
    }

    /**
     * appKey验证
     */
    @Before("getAppKeyPointCut()")
    public void doToken(JoinPoint joinPoint) {
        HttpServletRequest request = getHttpServletRequest();
        String appKey = request.getHeader("appKey");
        if(ObjectUtil.isEmpty(appKey)){
            throw new ServiceException(500,"appKey不存在");
        }else {
            //校验token是否正确
            ThirdPartyInterconnection thirdPartyInterconnection = thirdPartyInterconnectionService.getByAppKey(appKey);
            if(ObjectUtil.isNull(thirdPartyInterconnection)){
                throw new ServiceException(500,"appKey错误");
            }
        }
    }

    private static HttpServletRequest getHttpServletRequest(){
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;
        assert servletRequestAttributes != null;
        return servletRequestAttributes.getRequest();
    }

}
